<template>
	<z-nav-bar :title="title"></z-nav-bar>
	<view class="top-box">
		<view class="item flex_sbc">
			<view class="z-font-32">课程名称</view>
			<view class="flex_sbc input-box">
				<input
					v-model="course.name"
					type="text"
					placeholder="请输入课程名称"
					placeholder-class="uni-placeholder"
				/>
			</view>
		</view>
		<view class="item flex_sbc">
			<view class="z-font-32">授课时间</view>
			<view>
				<uni-datetime-picker v-model="course.beginTime" :start="startNum">
					<view class="flex_sbc input-box">
						<view v-if="course.beginTime">{{ course.beginTime }}</view>
						<view v-else class="uni-placeholder">请选择课程时间</view>
						<image
							:src="setting.oss_pub_domain + '/app-img/icon/icon_drop-down.png'"
							class="icon-size-32"
						></image>
					</view>
				</uni-datetime-picker>
			</view>
		</view>
		<view class="item flex_sbc">
			<view class="z-font-32">课程课时</view>
			<view class="flex_sbc input-box">
				<input
					v-model="course.duration"
					type="digit"
					placeholder="请输入课时"
					placeholder-class="uni-placeholder"
				/>
			</view>
		</view>
	</view>
	<view class="common-box">
		<view class="flex_sbc">
			<view class="z-font-28">选择已有课包</view>
			<view v-if="!course.id" class="create-package" @click="packageEditRef.open({}, -1)">新建课包</view>
		</view>
		<view v-if="packageList.length" class="package-list">
			<view v-for="(item, index) in  packageList" :key="item.id" :class="['package-item', 'flex_fsc', course.coursePackageIds == item.id ? 'active' : 'disable']" @click="course.id ? tools.alert('不允许更换课时包') : course.coursePackageIds = item.id">
				<image :src="item.images" class="cover" mode="aspectFill"></image>
				<view class="width-100">
					<view class="width-100 flex_sbc">
						<view class="u-line-1">{{ item.names }}</view>
						<image :src="setting.oss_pub_domain + '/app-img/icon/icon_edit-grey.png'" class="icon-size-32 flex_sh" @click.stop="packageEditRef.open(item, index)"></image>
					</view>
					<view class="z-font-24 uni-mt-8" style="color: #8A8F99;">课包类型：{{ item.type == 1 ? '课时包' : item.type == 2 ? '限时包' : '' }}</view>
					<view class="z-font-24 uni-mt-8" style="color: #8A8F99;">总课时：{{ item.number || 0 }}课时</view>
				</view>
			</view>
		</view>
		<z-no-data v-else placeholder="暂无课包"></z-no-data>
	</view>
	<view class="common-box">
		<view class="add-box">
			<view class="z-font-32">
				<text>添加需要解决的训练问题</text>
				<text style="color: #A8ABB3;"> (非必填)</text>
			</view>
			<z-add-button text="新增问题" @click="addObj(0)" class="uni-my-40"></z-add-button>
		</view>
		<view v-for="(question, index) in course.relQuestionSchemeList" :key="question.id" class="question-item">
			<view class="flex_sbc">
				<view class="z-font-32">{{ question.name }}</view>
				<uni-icons
					type="clear"
					color="#FF0000"
					size="22"
					@click="course.relQuestionSchemeList.splice(index, 1)"
				></uni-icons>
			</view>
			<view class="uni-color-grey z-font-24 uni-mt-8">
				关联解决方案{{ question.schemeList ? question.schemeList.length : 0 }}个
			</view>
			<view class="flex_sbc uni-mt-68 uni-mb-32">
				<view>解决方案</view>
				<view class="add" @click="addObj(1, index)">添加</view>
			</view>
			<view v-for="(scheme, sindex) in question.schemeList || []" :key="scheme.id" class="plan-item flex_fsc">
				<image :src="setting.oss_pub_domain + scheme.coverImage" mode="aspectFill" class="img"></image>
				<view class="uni-ml-20 width-100">
					<view class="flex_sbc width-100">
						<view>{{ scheme.name }}</view>
						<view class="uni-red flex_sh" @click="question.schemeList.splice(sindex, 1)">删除</view>
					</view>
					<view class="z-font-24 uni-color-grey uni-mt-8 uni-mt-16">{{ scheme.description }}</view>
				</view>
			</view>
		</view>
	</view>
	<bottom-box :buts="buts" @change="submit"></bottom-box>
	<package-edit ref="packageEditRef" @done="getCoursePackageList"></package-edit>
</template>

<script setup>
import { onLoad } from '@dcloudio/uni-app';
import { ref, reactive, getCurrentInstance } from 'vue';
import { addCoursePlan, editCoursePlan, getPackageList } from '@/api/player.js';
import { appointmentGiveLessonsDetail } from '@/api/course';
import PackageEdit from '../course/package';
const { proxy: that } = getCurrentInstance();

const eventChannel = that.getOpenerEventChannel(),
	noQuestion = ref(1);


const course = reactive(uni.getStorageSync('edit-course') || {}),
	playerInfo = uni.getStorageSync('player-info');
const title = course.id ? '编辑课程' : '新增课程';
if (course.id) {
	appointmentGiveLessonsDetail(course.id).then((res) => {
		Object.assign(course, res);
	});
} else {
	course.name = '课程' + that.tools.formatDate()
}
	

function addObj(type, index) {
	uni.navigateTo({
		url: `/pages/player/add/item-scheme/item-scheme?type=${type}`,
		events: {
			selObj: (data) => {
				if (type) course.relQuestionSchemeList[index].schemeList = data;
				else course.relQuestionSchemeList = data;
				that.$forceUpdate();
			}
		},
		success: (res) => {
			res.eventChannel.emit(
				'list',
				type ? course.relQuestionSchemeList[index].schemeList : course.relQuestionSchemeList
			);
		}
	});
}

const buts = [
	{
		label: '确定',
		bgColor: 'uni-color-main-bg'
	}
];

function submit() {
	if (!course.beginTime) return that.tools.alert('请输选择授课时间');
	if (!course.duration) return that.tools.alert('请输入课时');
	let relQuestionScheme = {};
	if (course.relQuestionSchemeList && course.relQuestionSchemeList.length) {
		const resultTmp = JSON.parse(course.result || '{}');
		course.result = {};
		course.relQuestionSchemeList.forEach((item) => {
			relQuestionScheme[item.id] = item.schemeList ? item.schemeList.map((el) => el.id) : [];
			const trainingPoints = {};
			if (item.schemeList) {
				item.schemeList.forEach((qs) => {
					trainingPoints[qs.id] =
						resultTmp[item.id] && resultTmp[item.id].trainingPoints[qs.id]
							? resultTmp[item.id] && resultTmp[item.id].trainingPoints[qs.id]
							: [];
				});
			}
			course.result[item.id] = {
				trainingState: resultTmp[item.id]?.trainingState || false,
				summaryComment: resultTmp[item.id]?.summaryComment || [],
				trainingPoints
			};
		});
		course.result = JSON.stringify(course.result);
	}
	const { id, serialNumber, name, duration, beginTime, result, coursePackageIds } = course;
	const postData = {
		serialNumber,
		name,
		duration,
		beginTime,
		stuId: playerInfo.id,
		result,
		type: 0,
		coursePackageIds
	};
	if (Object.keys(relQuestionScheme).length) postData.relQuestionScheme = JSON.stringify(relQuestionScheme);
	const funName = id ? editCoursePlan : addCoursePlan;
	funName(postData, id).then((res) => {
		const tmpId = id ? id : res.id;
		appointmentGiveLessonsDetail(tmpId).then((cData) => {
			eventChannel.emit('editDone', cData);
		});
		uni.navigateBack();
	});
}

const startNum = Date.now();

const packageList = ref([]), packageEditRef = ref('')
function getCoursePackageList() {
	getPackageList({ pageSize: 99, pageNum: 1, stuId: playerInfo.id }).then(res => {
		res.rows.forEach(item => {
			if (item.type === 2) item.validityDate = item.validityDate.split('T')[0]
			if (!course.id && item.isDefault) course.coursePackageIds = item.id
		})
		packageList.value = res.rows
	})
}
getCoursePackageList()
</script>

<style lang="scss">
@import '@/pages/course/edit/edit.scss';
.create-package {
		width: 108rpx;
		height: 40rpx;
		line-height: 40rpx;
		text-align: center;
		border-radius: 20rpx;
		border: 2rpx solid $uni-text-color-main;
		color: $uni-text-color-main;
		font-size: 24rpx;
	}
</style>
